﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using libAddressBook.BUS;
using libDAL;
using Telerik.WinControls.UI;
using libCommonTools.BUS;
using libCommonTools.Forms;

namespace libAddressBook.FORMS
{
    public partial class frmAddressBook : Telerik.WinControls.UI.RadForm
    {
        private clsUsersMainBUSInterface _BUSMain;
        private clsBUSInterfaceCompanyHistory _BUSHistory;
        private DataRow[] drCompanyOperational;
        private string strCompanyID = string.Empty;
        private string strCompanyType = string.Empty;
        private string strCommandType = string.Empty;
        private Boolean bolSelectedRow = false;

        public frmAddressBook()
        {
            InitializeComponent();
        }
        private void radLabel30_Click(object sender, EventArgs e)
        {

        }

        ~frmAddressBook()
        { }

        private void set_CancelChanges()
        {
            try
            {
                _BUSMain.set_RejectChangesMain();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "  frmAddressBook_set_CancelChanges"); 
            }
        }

        public void getset_CommandType(string strCommand)
        {
            try
            {
                //add security feature in this part, to verify for user permission or validation
                //add also a common function that are common in all module, as this moment it' still under study;
                this.strCommandType = strCommand;
                if (strCommand == "AddNew")
                {
                   // set_ClearentryFields();
                }
                else if (strCommand == "Edit")
                {
                   // set_ClearentryFields();
                }
                else if (strCommand == "Cancel")
                {
                    set_CancelChanges();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "  frmAddressBook_getset_CommandType"); 
            }
        }
      
        public  string getset_CompanyType
        {
            get
            {
                return strCompanyType;
            }
            set
            {
                strCompanyType = value;
            }
        }

        public string getset_CompanyID
        {
            get
            {
                return strCompanyID;
            }
            set
            {
                strCompanyID = value;
            }
        }


        private void cbbBranch_Click(object sender, EventArgs e)
        {
            try
            {
                frmAddressBookBranch frmBranch = new frmAddressBookBranch();
                frmBranch.ShowDialog(this);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "  frmAddressBook_cbbBranch_Click");
            }
        }

        private void btnUpdateAddress_Click(object sender, EventArgs e)
        {
            try
            {
                frmManageCompanyInfo frmAddressBook = new frmManageCompanyInfo();
                Point p = gbCredentials.PointToScreen(btnAddressHistory.Location);
                frmAddressBook.set_NewLocation(p.X, p.Y + btnAddressHistory.Height);
                frmAddressBook.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "  frmAddressBook_btnUpdateAddress_Click"); 
            }
        }

        private void set_ClearGrid()
        {
            dgvBranches.ClearSelection();
            this.dgvBranches.CurrentRow = null;
            this.dgvBranches.TableElement.Update(GridUINotifyAction.StateChanged);
        }

        private DataTable get_TemporaryForUpdateDataTable
        {
            get
            {
                DataTable dtTempHolder = new DataTable();
                dtTempHolder = (DataTable)dgvBranches.DataSource;
                return dtTempHolder;
            }
        }

        public bool set_SaveRecords()
        {
            bool bolStatus = false;
            try
            {
                if (get_CheckRequiredFields() == true)
                {
                     if (set_UpdateGridRow() == true)
                     {
                           dgvBranches.EndEdit();
                            if (_BUSMain.set_UpdateAddressBookdt(get_TemporaryForUpdateDataTable) == true)
                            {
                                if (_BUSMain.set_UpdateMainAddressBook() == true)
                                {
                                    if (_BUSHistory.set_UpdateCustomerHistory(get_CurrentRowSelectedDetails()) == true)
                                    {
                                        set_HQDetails();
                                        MessageBox.Show("Saved.");
                                        set_BindDatasource();
                                        set_ClearGrid();
                                    }
                                }
                            }
                     }
                     else if (this.strCommandType == "AddNew")
                     {

                     }
                }
                else
                {
                    MessageBox.Show("Fields Required, please try again"); 
                }
               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "  frmAddressBook_set_SaveRecords"); 
            }
            return bolStatus;
        }



        private void set_LoadAllRecords()
        {
            try
            {
             //   MessageBox.Show(chkInnactiveActive.Text + " 2");
                if (getset_CompanyID.Trim() != string.Empty && getset_CompanyType.Trim() != string.Empty)
                {
                    //MessageBox.Show(chkInnactiveActive.Text + " 3");
                    if (_BUSMain.set_CompanyDetails(getset_CompanyID, getset_CompanyType) == true)
                    {
                   //     MessageBox.Show(chkInnactiveActive.Text + " 4");
                        DataRow[] drCheck = _BUSMain.get_CompanyDetails(getset_CompanyID);
                        if (drCheck.Length > 0)
                        {
                            set_BindRecords();
                        }
                    }
                    //gets all the history of each branches
                    if (_BUSHistory.set_Records(getset_CompanyID) == true)
                    {

                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "  frmAddressBook_set_LoadAllRecords"); 
            }
        }

        public void set_AddressbookFields()
        {
            try
            {
                //gets all each branches belonging to the HQ ID
                set_LoadAllRecords();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "  frmAddressBook_set_AddressbookFields"); 
            }
        }

        public DataRow[] getset_SelectedCompanyForOperational
        {
            get
            {
                return this.drCompanyOperational = _BUSMain.get_AllCompany.Select("comid = '" + getset_CompanyID + "'");
            }
            set
            {
                this.drCompanyOperational = value;
            }
        }

        private void set_HQDetails()
        {
            try
            {
                DataTable dt = new DataTable();
                dt = _BUSMain.get_AllCompany;
                DataRow[] drHQ = dt.Select("acccode = 'H'");
                if (drHQ.Length > 0)
                {
                    txtHQtID.Text = drHQ[0]["comid"].ToString();
                    txtHQName.Text = drHQ[0]["comname"].ToString();
                    txtHQCountryCode.Text = drHQ[0]["coucode"].ToString();
                    txtHQStateCode.Text = drHQ[0]["stacode"].ToString();
                    txtHQCityCode.Text = drHQ[0]["citycode"].ToString();
                    txtHQAreaCode.Text = drHQ[0]["areacode"].ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "  frmAddressBook_set_HQDetails"); 
            }
        }

        private void set_BindDatasource()
        {
            if (getset_CompanyID.Trim() != string.Empty)
            {
                dgvBranches.DataSource = _BUSMain.get_AllCompany;
            }
        }

        private void set_BindRecords()
        {
            try
            {
                
                set_BindDatasource();
              
                for (int intCol = 0; intCol < dgvBranches.Columns.Count; intCol++)
                {
                    dgvBranches.Columns[intCol].BestFit();
                }

               
                set_HQDetails();
               
                set_ClearGrid();
            
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "  frmAddressBook_set_BindRecords"); 
            }
        }

        private bool set_CodeAndStatus()
        {
            bool bolStatus = false;
            try
            {
                if (chkHQ.Checked == true)
                {
                    for (int intRow = 0; intRow < dgvBranches.Rows.Count; intRow++)
                    {
                        dgvBranches.Rows[intRow].Cells["acccode"].Value = "B";
                    }
                    dgvBranches.CurrentRow.Cells["acccode"].Value = "H";
                }


                if (chkInnactiveActive.Checked == true)
                {
                    dgvBranches.CurrentRow.Cells["comStatus"].Value = 1;
                }
                else
                {
                    dgvBranches.CurrentRow.Cells["comStatus"].Value = 0;
                }
                bolStatus = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ""); 
            }
            return bolStatus;
        }

        private bool set_UpdateGridRow()
        {
            bool bolStatus = false;
            try
            {
                dgvBranches.CurrentRow.Cells["comid"].Value = txtID.Text.Trim();
                dgvBranches.CurrentRow.Cells["comregno"].Value = txtRegistrationNoReq.Text.Trim();
                dgvBranches.CurrentRow.Cells["comname"].Value = txtCompanyNameReq.Text.Trim();
                dgvBranches.CurrentRow.Cells["addline1"].Value = txtAddressLine1Req.Text.Trim();
                dgvBranches.CurrentRow.Cells["addline2"].Value = txtAddressLine2Req.Text.Trim();
                dgvBranches.CurrentRow.Cells["addline3"].Value = txtAddressLine3.Text.Trim();
                dgvBranches.CurrentRow.Cells["addline4"].Value = txtAddressLine4.Text.Trim();
                dgvBranches.CurrentRow.Cells["citycode"].Value = txtCityCodeReq.Text.Trim();
                dgvBranches.CurrentRow.Cells["coucode"].Value = txtCountryCodeReq.Text.Trim();
                dgvBranches.CurrentRow.Cells["stacode"].Value = txtStateCodeReq.Text.Trim();
                dgvBranches.CurrentRow.Cells["areacode"].Value = txtAreaCodeReq.Text.Trim();
                dgvBranches.CurrentRow.Cells["poscode"].Value = txtPostalCodeReq.Text.Trim();
                dgvBranches.CurrentRow.Cells["portid"].Value = txtZoneCode.Text.Trim();
                dgvBranches.CurrentRow.Cells["website"].Value = txtWebSite.Text.Trim();
                dgvBranches.CurrentRow.Cells["email"].Value = txtEmailReq.Text.Trim();
                dgvBranches.CurrentRow.Cells["contact"].Value = txtContactPersonReq.Text.Trim();
                dgvBranches.CurrentRow.Cells["faxno"].Value = txtContactNo.Text.Trim();
                
                if (set_CodeAndStatus() == true)
                {
                    bolStatus = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "  frmAddressBook_set_UpdateGridRow"); 
            }
            return bolStatus;
        }

        private void set_Fields()
        {
            try
            {
                if (dgvBranches.SelectedRows.Count > 0)
                {
                    txtID.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["comid"].Value).ToString().Trim();
                    txtRegistrationNoReq.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["comregno"].Value).ToString().Trim();
                    txtCompanyNameReq.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["comname"].Value).ToString().Trim();
                    txtAddressLine1Req.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["addline1"].Value).ToString().Trim();
                    txtAddressLine2Req.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["addline2"].Value).ToString().Trim();
                    txtAddressLine3.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["addline3"].Value).ToString().Trim();
                    txtAddressLine4.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["addline4"].Value).ToString().Trim();
                    txtCityCodeReq.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["citycode"].Value).ToString().Trim();
                    txtCountryCodeReq.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["coucode"].Value).ToString().Trim();
                    txtStateCodeReq.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["stacode"].Value).ToString().Trim();
                    txtAreaCodeReq.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["areacode"].Value).ToString().Trim();
                    txtPostalCodeReq.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["poscode"].Value).ToString().Trim();
                    txtZoneCode.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["portid"].Value).ToString().Trim();
                    txtWebSite.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["website"].Value).ToString().Trim();
                    txtEmailReq.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["email"].Value).ToString().Trim();
                    txtContactPersonReq.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["contact"].Value).ToString().Trim();
                    txtContactNo.Text = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["faxno"].Value).ToString().Trim();

                    getset_CompanyID = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["comid"].Value).ToString().Trim();
                    getset_CompanyType = clsGenFunction.get_checkStringNull(dgvBranches.CurrentRow.Cells["acccode"].Value).ToString().Trim();
                   
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "  frmAddressBook_set_Fields"); 
            }
        }

        private void frmAddressBook_Load(object sender, EventArgs e)
        {
            _BUSHistory = new clsBUSInterfaceCompanyHistory();
        }

        private void cbbOperational_Click(object sender, EventArgs e)
        {
            try
            {
                //frmOperationalSettings x = new frmOperationalSettings();
                //x.StartPosition = FormStartPosition.CenterScreen;
                //x.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "  frmAddressBook_cbbOperational_Click"); 
            }
        }

        private void frmAddressBook_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Dispose();
            GC.Collect();
            GC.WaitForFullGCComplete();
            GC.Collect();
        }

       
        private void radTextBox1_Click(object sender, EventArgs e)
        {
            //radTextBox1.SelectAll();
        }

        public void set_Refresh()
        {
            try
            {
                getset_SelectedRowStatus = false;
                set_ClearentryFields();
                set_LoadAllRecords();
                set_BindDatasource();
                set_ClearGrid();
                get_CheckExists();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "  frmAddressBook_set_Refresh"); 
            }
        }


        public void set_RefreshAll()
        {
            try
            {
               
                DataTable dt = new DataTable();
                dgvBranches.DataSource = dt;
                set_ClearentryFieldsAll();
                getset_SelectedRowStatus = false;
                _BUSMain = null;
                _BUSHistory = null;
                GC.Collect();
                getset_CompanyID = string.Empty;
                getset_CompanyType = string.Empty;
                _BUSMain = new clsUsersMainBUSInterface();
                _BUSHistory = new clsBUSInterfaceCompanyHistory();
                get_CheckExists();
                GC.Collect();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " frmAddressBook_set_RefreshAll"); 
            }
        }

        private void set_ClearentryFieldsAll()
        {
            txtHQtID.Text = string.Empty;
            txtHQStateCode.Text = string.Empty;
            txtHQName.Text = string.Empty;
            txtHQCountryCode.Text = string.Empty;
            txtHQCityCode.Text = string.Empty;
            txtHQAreaCode.Text = string.Empty;
            set_ClearentryFields();
        }

        private void set_ClearentryFields()
        {
            try
            {
                RadTextBox txtBax;
                foreach (Control ctrl in gbCredentials.Controls)
                {
                    RadControl rc = ctrl as RadControl;
                    if (rc != null)
                    {
                        if (rc.Name.Trim().Contains("HQ") == false)
                        {
                            if (rc.Name.Trim().Contains("Label") == false)
                            {
                                if (rc.Name.Trim().Contains("chk") == false)
                                {
                                    rc.Text = string.Empty;
                                    get_CheckFields(ref rc, "Refresh");
                                }
                            }
                        }
                    }
                }

                getset_CompanyID = string.Empty;
                getset_CompanyType = string.Empty;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " frmAddressBook_set_ClearentryFields"); 
            }
        }

        private void set_Reset()
        {
            _BUSMain = new clsUsersMainBUSInterface();
            _BUSHistory = new clsBUSInterfaceCompanyHistory();
        }

        

        private void frmAddressBuk_Load(object sender, EventArgs e)
        {
            _BUSMain = new clsUsersMainBUSInterface();
            _BUSHistory = new clsBUSInterfaceCompanyHistory();
            ((GridTableElement)this.dgvBranches.TableElement).RowHeight = 20;

            clsGenFunction.set_BackStage(ref pvAddressBook); 
        }

        private bool get_CheckExists()
        {
            bool bolStatus = false;
            try
            {
                bool bolMain = false;
                bool bolHistory = false;

                if (_BUSMain.get_CheckDatasetRows() == true)
                {
                    bolMain = _BUSMain.set_NewCompany();
                }

                if (_BUSHistory.get_checkHistoryRows() == true)
                {
                    bolHistory = _BUSHistory.set_NewCompanyHistory();
                }

                if (bolMain == true && bolHistory == true)
                {
                    bolStatus = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " frmAddressBook_get_CheckExists"); 
            }

            return bolStatus;
        }

       //checks for empty entry fields
        private bool get_CheckFields(ref RadControl rc, string strType)
        { 
             bool bolStatus = false;
             try
             {
                 if (rc.Name.Contains("chk") == false)
                 {
                     int intCount = 0;
                     RadTextBox txtBax = new RadTextBox();
                     RadDropDownList ddlList = new RadDropDownList();
                     Color clLocalColor;

                     #region ColorIdentification
                     if (rc.Text.Trim() == string.Empty && strType != "Refresh")
                     {
                         clLocalColor = Color.Orange;
                     }
                     else
                     {
                         clLocalColor = Color.White;
                         bolStatus = true;
                     }
                     # endregion

                     if (rc.Name.Contains("Req"))
                     {
                         //checks if empty
                         txtBax = new RadTextBox();
                         ddlList = new RadDropDownList();
                         //change backcolor of textbox
                         if (rc is RadTextBox)
                         {
                             txtBax = (RadTextBox)rc;
                             txtBax.TextBoxElement.BackColor = clLocalColor;
                             rc = txtBax;
                         }
                         else if (rc is RadDropDownList)
                         {
                             //change backcolor of dropdownlist
                             ddlList = (RadDropDownList)rc;
                             ddlList.DropDownListElement.EditableElement.BackColor = clLocalColor;
                             rc = ddlList;
                         }
                     }
                     else
                     {
                         bolStatus = true;
                     }
                 }
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message + " frmAddressBook_get_CheckFields"); 
             }
             return bolStatus;
        }

         private bool get_CheckRequiredFields()
        {
            bool bolStatus = false;
            try
            {
                int intCount = 0;
                //if (getset_CompanyID.Trim () != string.Empty) 
                //{
                    Control[] controls = {};
                    RadTextBox txtBax = new RadTextBox();
                    RadDropDownList ddlList = new RadDropDownList();

                    //loop through all the controls in the groupbox
                    foreach (Control ctrl in gbCredentials.Controls)
                    {
                        RadControl rc = ctrl as RadControl;
                        if (rc != null)
                        {
                            //verifies if either text or dropdownlist
                            if (rc is RadTextBox || rc is RadDropDownList)
                            {
                               //the control Name nust not have a string HQ
                                if (rc.Name.Contains("HQ") == false)
                                {
                                    if (rc.Name.Contains("chk") == false)
                                    {
                                        //find the specific control inside the groupbox                    
                                        if (rc.Text.Trim() == string.Empty)
                                        {
                                            //pass the control, type of color based on entry value;
                                            if (get_CheckFields(ref rc, "Check") == false)
                                            {
                                                intCount++;
                                            }
                                        }
                                        else if (rc.Text.Trim() != string.Empty)
                                        {
                                            if (get_CheckFields(ref rc, "Check") == false)
                                            {
                                                intCount++;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    // }
                }
                if (intCount == 0)
                {
                    bolStatus = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ""); 
            }
            return bolStatus;
        }

        private DataRow get_CurrentRowSelectedDetails()
        {
            DataTable dtx = (DataTable)dgvBranches.DataSource;
            DataTable dty = dtx.Clone();
            DataRow[] drInsert = dty.Select();
            DataRow dr = dtx.NewRow();

            try
            {
                for (int intCol = 0; intCol < dgvBranches.Columns.Count; intCol++)
                {
                    dr[intCol] = dgvBranches.CurrentRow.Cells[intCol].Value;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " frmAddressBook_get_CurrentRowSelectedDetails"); 
            }
            return dr;
        }

        private void btnUpdateAddress_Click_1(object sender, EventArgs e)
        {
            try
            {
                if (dgvBranches.SelectedRows.Count > 0)
                {
                    frmManageCompanyInfo CompanyInfo = new frmManageCompanyInfo();
                    CompanyInfo.set_DAL(ref _BUSHistory);
                    CompanyInfo.set_MainBUS(ref _BUSMain);
                    CompanyInfo.getset_CompanyHistoryID = dgvBranches.CurrentRow.Cells["companyHistoryID"].Value.ToString().Trim();
                    CompanyInfo.getset_CompanyID = dgvBranches.CurrentRow.Cells["comid"].Value.ToString().Trim();
                    CompanyInfo.getset_CompanyCurrentSelected = get_CurrentRowSelectedDetails();

                    DialogResult result = CompanyInfo.ShowDialog();

                    if (result == DialogResult.Cancel)
                    {
                        set_ClearentryFields();
                        set_ClearGrid(); 
                    }
                    else if (result == DialogResult.OK)
                    {
                        set_AlteredCompanyInformation(CompanyInfo.get_DefaultCompany());
                        set_Fields();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " frmAddressBook_btnUpdateAddress_Click_1"); 
            }
        }

        private bool set_AlteredCompanyInformation(DataRow drNew)
        {
            bool bolStatus = false;
            try
            {
                for (int intCol = 0; intCol < dgvBranches.Columns.Count; intCol++)
                {
                   this.dgvBranches.CurrentRow.Cells[intCol].Value = drNew[intCol];
                }
                bolStatus = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " frmAddressBook_set_AlteredCompanyInformation"); 
            }
            return bolStatus;
        }

        private void dgvBranches_CellClick(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
        {
            try
            {
                //set_ValuesInDatarow();
                set_Fields();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " frmAddressBook_dgvBranches_CellClick"); 
            }
        }

        private void dgvBranches_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                      set_Fields();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + " frmAddressBook_dgvBranches_CellClick");
                }
            }
        }

        public bool getset_SelectedRowStatus
        {
            get
            {
                return bolSelectedRow;
            }
            set
            {
                bolSelectedRow = value;
            }
        }

        private void dgvBranches_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvBranches.SelectedRows.Count > 0)
                {
                    getset_SelectedRowStatus = true;
                    set_Fields();
                    get_CheckRequiredFields();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " frmAddressBook_dgvBranches_CellClick");
            }
        }

        private void frmAddressBook_FormClosed_1(object sender, FormClosedEventArgs e)
        {
            set_RefreshAll();
            GC.Collect();
        }

        //this function must be in BUS not here
        private DataRow get_NewAddedCompany()
        {
            DataRow drNew = null;
            try
            {
                clsCommonFunctions _Common = new clsCommonFunctions();
                string strcomid = _Common.get_newCompanyID(txtCompanyNameReq.Text.Trim(), _BUSMain.get_DAL);
                txtID.Text = strcomid;
                getset_CompanyID = strcomid;

                DataRow drHolder = _BUSMain.get_AllCompany.NewRow();
                drHolder["comid"] = txtID.Text.Trim();
                drHolder["comregno"] = txtRegistrationNoReq.Text.Trim();
                drHolder["comname"] = txtCompanyNameReq.Text.Trim();
                drHolder["addline1"] = txtAddressLine1Req.Text.Trim();
                drHolder["addline2"] = txtAddressLine2Req.Text.Trim();
                drHolder["addline3"] = txtAddressLine3.Text.Trim();
                drHolder["addline4"] = txtAddressLine4.Text.Trim();
                drHolder["citycode"] = txtCityCodeReq.Text.Trim();
                drHolder["coucode"] = txtCountryCodeReq.Text.Trim();
                drHolder["stacode"] = txtStateCodeReq.Text.Trim();
                drHolder["areacode"] = txtAreaCodeReq.Text.Trim();
                drHolder["poscode"] = txtPostalCodeReq.Text.Trim();
                drHolder["portid"] = txtZoneCode.Text.Trim();
                drHolder["website"] = txtWebSite.Text.Trim();
                drHolder["email"] = txtEmailReq.Text.Trim();
                drHolder["contact"] = txtContactPersonReq.Text.Trim();
                drHolder["faxno"] = txtContactNo.Text.Trim();

                if (txtHQtID.Text.Trim() == string.Empty && txtHQName.Text.Trim() == string.Empty)
                {
                    drHolder["comidHQ"] = txtID.Text.Trim() + "_" + txtCompanyNameReq.Text.Trim();
                    drHolder["acccode"] = "H";
                    drHolder["comDefault"] = 1;
                }
                else
                {
                    drHolder["acccode"] = "B";
                    drHolder["comidHQ"] = txtHQtID.Text.Trim() + "_" + txtHQName.Text.Trim();
                    drHolder["comDefault"] = 1;
                }
                drHolder["companyHistoryID"] = txtID.Text.Trim() + "_" + clsGenFunction.get_GenKeyNEWID(_BUSMain.get_DAL); 

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " frmAddressBook_get_NewAddedCompany"); 
            }
            return drNew;
        }

        private void set_HeaderMainOfficeDetails()
        {
            clsCommonFunctions _Common = new clsCommonFunctions();
            txtHQName.Text = txtCompanyNameReq.Text.Trim();
            txtHQAreaCode.Text = txtAreaCodeReq.Text.Trim();
            txtHQCityCode.Text = txtCityCodeReq.Text.Trim();
            txtHQCountryCode.Text = txtCountryCodeReq.Text.Trim();
            txtHQStateCode.Text = txtStateCodeReq.Text.Trim();

            txtHQtID.Text = _Common.get_newCompanyID(txtCompanyNameReq.Text.Trim(), _BUSMain.get_DAL); ;
        }

        public bool set_AddNewCompany()
        {
            bool bolStatus = false;
            try
            {
                if (get_CheckRequiredFields() == true)
                {
                   get_CheckExists();
                   if (_BUSMain.set_AddNewCompany(get_NewAddedCompany()) == true)
                   {
                       if (_BUSMain.get_checkRecordCountHQExists() == true)
                       {
                           //set the header values. The veri first record is set as Default Main office
                            set_HeaderMainOfficeDetails();
                       }
                            dgvBranches.DataSource = _BUSMain.get_AllCompany;
                            set_ClearGrid();
                            set_ClearentryFields();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "  frmAddressBook_set_AddNewCompany"); 
            }
            return bolStatus;
        }

        private void txtCityCodeReq_Click(object sender, EventArgs e)
        {
            RadControl rc = sender as RadControl;
            MessageBox.Show(rc.Name.Trim()); 
        }

        private void txtCityCodeReq_MouseClick(object sender, MouseEventArgs e)
        {

        }

        private void set_AddressbookCriteria(ref frmFindCompany Find, string strControlName)
        {
            if (strControlName.Trim().Contains("City"))
            {
                Find.getset_SearchType = "City";
            }
            else if (strControlName.Trim().Contains("Area"))
            {
                Find.getset_SearchType = "Area";
            }
            else if (strControlName.Trim().Contains("State"))
            {
                Find.getset_SearchType = "State";
            }
            else if (strControlName.Trim().Contains("Country"))
            {
                Find.getset_SearchType = "Country";
            }
            else if (strCommandType.Trim().Contains("Zone"))
            {
                Find.getset_SearchType = "Zone";
            }
            else if (strControlName.Trim().Contains("Port"))
            {
                Find.getset_SearchType = "Port";
            }
        }

        private void set_AddressCodesEntryExceptZone(ref frmFindCompany addressBook, string strType)
        {
            try
            {
                if (strType.Trim().ToLower().Contains("area") == true)
                {
                    txtCityCodeReq.Text = addressBook.get_CityCode;
                    lblCity.Text = addressBook.get_CityName;

                    txtAreaCodeReq.Text = addressBook.get_AreaCode;
                    lblAreaCode.Text = addressBook.get_AreaName;

                    txtStateCodeReq.Text = addressBook.get_StateCode;
                    lblState.Text = addressBook.get_StateName;

                    txtCountryCodeReq.Text = addressBook.get_CountryCode;
                    lblCountry.Text = addressBook.get_CountryName;
                }
                else if (strType.Trim().ToLower().Contains("city") == true)
                {
                    txtCityCodeReq.Text = addressBook.get_CityCode;
                    lblCity.Text = addressBook.get_CityName;

                    txtStateCodeReq.Text = addressBook.get_StateCode;
                    lblState.Text = addressBook.get_StateName;

                    txtCountryCodeReq.Text = addressBook.get_CountryCode;
                    lblCountry.Text = addressBook.get_CountryName;
                }
                else if (strType.Trim().ToLower().Contains("state") == true)
                {
                    txtStateCodeReq.Text = addressBook.get_StateCode;
                    lblState.Text = addressBook.get_StateName;

                    txtCountryCodeReq.Text = addressBook.get_CountryCode;
                    lblCountry.Text = addressBook.get_CountryName;
                }
                else if (strType.Trim().ToLower().Contains("country") == true)
                {
                    txtCountryCodeReq.Text = addressBook.get_CountryCode;
                    lblCountry.Text = addressBook.get_CountryName;
                }
                else if (strType.Trim().ToLower().Contains("port") == true)
                {
                    txtPortID.Text = addressBook.get_PortID;
                    lblPortName.Text = addressBook.get_PortName; 
                }
                else if (strType.Trim().ToLower().Contains("post") == true)
                {
                    txtPostalCodeReq.Text = addressBook.get_PostCode;
  
                    //txtpost = addressBook.get_PortID;
                    //lblPortName.Text = addressBook.get_PortName; 
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " set_AddressCodesEntryExceptZone"); 
            }
        }

        private void set_addressCodeZone(ref frmFindCompany Find)
        {
            txtZoneCode.Text = Find.get_ZoneCode;
            lblZone.Text = Find.get_ZoneName;
        }

        private void txtCityCodeReq_Enter(object sender, EventArgs e)
        {
            try
            {
                    frmFindCompany addressBook = new frmFindCompany();
                    RadControl rc = sender as RadControl;

                    if (rc.Name.Trim().Contains("Zone") == false 
                        && rc.Name.Trim().Contains("Port") == false 
                        && rc.Name.Trim().Contains("Post") == false)
                    {
                        addressBook = new frmFindCompany("AddressDetails");
                    }
                    else if (rc.Name.Trim().Contains("Port") == true)
                    {
                        addressBook = new frmFindCompany("Port");
                    }
                    else if (rc.Name.Trim().Contains("Post") == true)
                    {
                        addressBook = new frmFindCompany("Post");
                    }
                    else
                    {
                        addressBook = new frmFindCompany("Zone");
                    }

                    set_AddressbookCriteria(ref addressBook,rc.Name.Trim());
                    DialogResult dlResult = addressBook.ShowDialog();
                    if (dlResult == DialogResult.OK)
                    {
                        if (rc.Name.Trim().Contains("Zone") == true)
                        {
                            set_addressCodeZone(ref addressBook);
                        }
                        else
                        {
                            set_AddressCodesEntryExceptZone(ref addressBook, rc.Name.Trim());
                        }
                    }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " frmAddressBook_txtCityCodeReq_Enter"); 
            }
        }

        private void gbCredentials_Click(object sender, EventArgs e)
        {

        }

        private void btnContactPerson_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtID.Text.Trim() != string.Empty)
                {
                    frmContacts Contacts = new frmContacts();
                    Contacts.set_DataAccess = _BUSMain.get_DAL;
                    Contacts.getset_Type = "Contacts";
                    Contacts.getset_CompanyID = txtID.Text.Trim();
                    Contacts.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + " frmAddressBook_btnContactPerson_Click"); 
            }
        }
    }
}
